package com.sky.edumanageapi.user.dao.repository.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.sky.edumanageapi.user.dao.mapper.UserMapper;
import com.sky.edumanageapi.user.dao.repository.UserRepository;
import com.sky.edumanageapi.user.pojo.po.UserPO;
import com.sky.edumanageapi.user.pojo.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.Date;

@Repository
public class UserRepositoryImpl implements UserRepository {

    @Autowired
    private UserMapper userMapper;


    @Override
    public void insert(UserPO userPO) {
        userMapper.insert(userPO);
    }

    @Override
    public UserPO getUserByUsername(String username) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("username", username);
        return userMapper.selectOne(queryWrapper);
    }

    @Override
    public void updateUser(UserPO userPO) {
        if (userPO.getUserId() == null) {
            throw new IllegalArgumentException("用户ID不能为空");
        }
        UpdateWrapper<UserPO> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("user_id", userPO.getUserId());
        // 字符串字段校验：非空且非空字符串
        updateWrapper.set(hasText(userPO.getUsername()), "username", userPO.getUsername())
                .set(hasText(userPO.getPassword()), "password", userPO.getPassword())
                .set(hasText(userPO.getEmail()), "email", userPO.getEmail())
                .set(hasText(userPO.getPhone()), "phone", userPO.getPhone())
                .set(hasText(userPO.getAvatar()), "avatar", userPO.getAvatar())
                .set(hasText(userPO.getNickname()), "nickname", userPO.getNickname())
                .set(userPO.getGender() != null, "gender", userPO.getGender())
                .set(userPO.getStatus() != null, "status", userPO.getStatus())
                .set("update_time", new Date());        // 强制更新时间为当前时间
        userMapper.update(null, updateWrapper);
    }

    @Override
    public UserPO getUserById(Integer id) {
        QueryWrapper<UserPO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",id);

        return userMapper.selectOne(queryWrapper);
    }


    public static boolean hasText(String str) {
        return str != null && !str.trim().isEmpty();
    }
}
